package chat

import (
	"coze_for_sdk/controller"
	"coze_for_sdk/logger"
	"coze_for_sdk/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {

	conversationId := c.Query("conversation_id")
	lastId, _ := strconv.Atoi(c.Query("last_id"))
	userId := c.GetInt("user_id")
	page := c.Query("page")
	pageInt, _ := strconv.Atoi(page)
	pageSize := c.Query("page_size")
	pageSizeInt, _ := strconv.Atoi(pageSize)
	offset := (pageInt - 1) * pageSizeInt

	if conversationId == "" {
		controller.Fail(c, controller.ParamsError, "会话ID不能为空")
		return
	}

	db := model.GetInstance().GetDB()

	//会话查询
	var conversation model.CozeConversation
	conversation, err := conversation.GetConversation(conversationId, userId)
	if err != nil {
		controller.Fail(c, controller.BusinessError, "会话不存在")
		return
	}

	//聊天记录查询
	var chats []model.CozeChat
	query := db.Model(&model.CozeChat{}).
		Debug().
		Where("conversation_id = ?", conversationId).
		Where("status = ?", model.CozeChatStatusActive)

	if lastId != 0 {
		query = query.Where("id < ?", lastId)
	}

	if err = query.Order("created_at desc").
		Offset(offset).
		Limit(pageSizeInt).
		Find(&chats).Error; err != nil {
		logger.Error("查询聊天记录失败: %v", err)
		controller.Fail(c, controller.BusinessError, "查询聊天记录失败")
		return
	}

	//聊天记录转换
	var response []map[string]interface{}
	for _, chat := range chats {
		response = append(response, map[string]interface{}{
			"id":           chat.Id,
			"content":      chat.Content,
			"content_type": chat.ContentType,
			"type":         chat.Type,
			"created_at":   chat.CreatedAt.Format("2006-01-02 15:04"),
		})
	}

	//聊天记录总数
	var total int64
	db.Model(&model.CozeChat{}).
		Where("conversation_id = ?", conversationId).
		Where("status = ?", model.CozeChatStatusActive).
		Count(&total)

	controller.Success(c, map[string]interface{}{
		"list":  response,
		"total": total,
	})

}
